package cn.edu.njust.service.impl;

import cn.edu.njust.core.enums.RoleEnum;
import cn.edu.njust.core.exception.BusinessException;
import cn.edu.njust.core.exception.ParamsException;
import cn.edu.njust.mapper.UserMapper;
import cn.edu.njust.pojo.po.User;
import cn.edu.njust.service.SystemService;
import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 系统业务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SystemServiceImpl implements SystemService {

    private final UserMapper userMapper;

    @Override
    public User login(User loginUser) {
        User dbUser = userMapper.selectByCodeAndPassword(loginUser.getCode(), loginUser.getPassword());
        if (Objects.isNull(dbUser)) {
            throw new ParamsException("用户名或密码错误！");
        }
        return dbUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void freshAllStatus() {
        // 重新设置状态
        userMapper.refreshSignInStatus();
        // 清空请假列表
        userMapper.cleanAllLeaves();
    }

    @Override
    public void addUser(User user) {
        User dbUser = userMapper.selectByCode(user.getCode());
        if (Objects.nonNull(dbUser)) {
            log.error("该工号已存在！");
            throw new BusinessException("该工号已存在！");
        }
        List<User> manageUsers = userMapper.queryUserByClassNumber(user.getClassNumber());
        if (CollUtil.isNotEmpty(manageUsers)) {
            manageUsers.forEach(manageUser -> {
                if (Objects.equals(manageUser.getRole(), RoleEnum.MONITOR.getCode())) {
                    user.setMonitorId(manageUser.getId());
                }
                if (Objects.equals(manageUser.getRole(), RoleEnum.SECRETARY.getCode())) {
                    user.setSecretaryId(manageUser.getId());
                }
            });
        }
        userMapper.add(user);
    }
}
